package com.justspeak;

import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ExpandableListView;
import android.widget.SimpleAdapter;

import com.justspeak.download.HttpDownloader;
import com.justspeak.module.CourseInfo;
import com.justspeak.module.CourseInfoAdapter;
import com.justspeak.module.UnitInfo;
import com.justspeak.util.xml.CourceListContentHandle;
import com.justspeak.util.xml.UnitListContentHandle;

/**
 * copyright justspeak 2010
 * 
 * @date 2011-9-15 V1.0初始作成
 * @author zhouhongbing
 * @version V1.0
 * @brief CourseListActivity的定义
 * @since 1.0
 * @history 2011-9-15 V1.X 修改内容，一个版本一行
 * @descript 对课程列表的操作
 * @todo 未完成的事项
 */
public class CourseListActivity extends Activity implements
	ExpandableListView.OnGroupClickListener,
	ExpandableListView.OnChildClickListener {

    private List<UnitInfo> groups;
    private List<CourseInfo> lessons=new ArrayList<CourseInfo>();
    private CourseInfoAdapter exlist_adapter = null;

    private ExpandableListView exlist;
    /**
     * Called when the activity is first created
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     **/
    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	// 加载layout

	setContentView(R.layout.course_list);

	// 取得listview

	exlist = (ExpandableListView) findViewById(R.id.course_list);

	// 调用init方法，这个方法主要是,初始化一些数据

	init();

	// 构建expandablelistview的适配器

	exlist_adapter = new CourseInfoAdapter(this, groups);

	exlist.setOnChildClickListener(this);

	exlist.setAdapter(exlist_adapter); // 绑定视图－适配器

    }

    
    
   



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// TODO Auto-generated method stub
	menu.add(Menu.NONE, Menu.FIRST + 1, 0, "下载");
	menu.add(Menu.NONE,Menu.FIRST+2,1,"退出");
	
	return true;
    }







    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	switch (item.getItemId()) {
	case Menu.FIRST+1:
	    Intent intent=new Intent(this,FileDownManageActivity.class);
	    getSelectedLesson(groups);	//得到选中的课程lessons
	    intent.putExtra("lessons", (Serializable)lessons);
	    startActivity(intent);
	    break;

	default:
	    finish();
	    break;
	}
	return super.onOptionsItemSelected(item);
    }


    /**
     * 得到选中的课程
     * @param unitInfos
     * @return
     */
    private List<CourseInfo> getSelectedLesson(List<UnitInfo> unitInfos){
     if(unitInfos!=null){
	for (UnitInfo unitInfo : unitInfos) {
	   List<CourseInfo> cours= unitInfo.getChildren();
	   for (CourseInfo courseInfo : cours) {
	    if(courseInfo.isChecked()==true){
		lessons.add(courseInfo);
	    }
	}
	}
     }
	return lessons; 
    }




    private void init() {
	// 1 读取课程xml文件，转化为courseItem对象集合
//	String xml = this.dowloadXML(getText(R.string.course_url).toString()
//		+ "CourseList.xml");
//	String xmlUnits = this.dowloadXML(getText(R.string.course_url)
//		.toString()
//		+ "UnitList.xml");
//	List<UnitInfo> unitInfos = this.parse2Unit(xmlUnits);
//	List<CourseInfo> courseInfos = this.parse(xml);
	List<UnitInfo> unitInfos = initUnits();
	List<CourseInfo> courseInfos = initCourseInfos();
	
	// 2 使courseItems对象绑定到SampleAdapter,为listView绑定simpleAdapter数据集
	groups = new ArrayList<UnitInfo>();
	List<CourseInfo> courseInfosTemp = null;
	// 构建List用作group1的子项

	// 往List中添加内容
	for (UnitInfo unitInfo : unitInfos) {
	    courseInfosTemp = new ArrayList<CourseInfo>();
	    for (CourseInfo courseInfo : courseInfos) {

		if (unitInfo.getUnit().equals(courseInfo.getUnit())) {
		    courseInfosTemp.add(courseInfo);
		}
	    }
	    unitInfo.setChildren(courseInfosTemp);
	    groups.add(unitInfo);
	}

    }

    private List<CourseInfo> initCourseInfos(){
	List<CourseInfo> retInfos=new ArrayList<CourseInfo>();
	CourseInfo c1=new CourseInfo();
	c1.setId("0001");
	c1.setBook("餐厅英语");
	c1.setUnit("01");
	c1.setUnitname("预订");
	c1.setMp3Name("预订服务.mp3");
	c1.setMp3Size("4574145");
	c1.setLrcName("a1.lrc");
	c1.setLrcSize("124");
	c1.setChecked(false);

	CourseInfo c2=new CourseInfo();
	c2.setId("0002");
	c2.setBook("餐厅英语");
	c2.setUnit("01");
	c2.setUnitname("预订");
	c2.setMp3Name("预定宴席服务.mp3");
	c2.setMp3Size("4055458");
	c2.setLrcName("a2.lrc");
	c2.setLrcSize("1280");
	c2.setChecked(false);
	
	CourseInfo c3=new CourseInfo();
	c3.setId("0003");
	c3.setBook("餐厅英语");
	c3.setUnit("02");
	c3.setUnitname("餐厅服务");
	c3.setMp3Name("泊车服务.mp3");
	c3.setMp3Size("3250887");
	c3.setLrcName("a3.lrc");
	c3.setLrcSize("1.28kb");
	c3.setChecked(false);
	
	CourseInfo c4=new CourseInfo();
	c4.setId("0004");
	c4.setBook("餐厅英语");
	c4.setUnit("03");
	c4.setUnitname("服务");
	c4.setMp3Name("引座服务.mp3");
	c4.setMp3Size("3295190");
	c4.setLrcName("a3.lrc");
	c4.setLrcSize("1.28kb");
	c4.setChecked(false);
	
	retInfos.add(c1);
	retInfos.add(c2);
	retInfos.add(c3);
	retInfos.add(c4);
	return retInfos;
    }
    private List<UnitInfo> initUnits(){
	List<UnitInfo> retInfos=new ArrayList<UnitInfo>();
	UnitInfo u1=new UnitInfo();
	u1.setId("0001");
	u1.setBook("餐饮英语");
	u1.setUnit("01");
	u1.setTitle("单元："+u1.getUnit()+"预订");
	u1.setCourseCount(2);
	u1.setChecked(false);
	u1.setChildren(null);
	
	UnitInfo u2=new UnitInfo();
	u2.setId("0003");
	u2.setBook("餐饮英语");
	u2.setUnit("02");
	u2.setTitle("单元："+u2.getUnit()+"餐厅服务");
	u2.setCourseCount(1);
	u2.setChecked(false);
	u2.setChildren(null);
	
	UnitInfo u3=new UnitInfo();
	u3.setId("0003");
	u3.setBook("餐饮英语");
	u3.setUnit("03");
	u3.setTitle("单元："+u3.getUnit()+"服务");
	u3.setCourseCount(1);
	u3.setChecked(false);
	u3.setChildren(null);
	
	retInfos.add(u1);
	retInfos.add(u2);
	retInfos.add(u3);
	return retInfos;
    }
    
    
    private String dowloadXML(String urlString) {
	HttpDownloader httpDownloader = new HttpDownloader();
	return httpDownloader.download(urlString);

    }

    /**
     * 将课程xml转化为courseInfo集合
     * 
     * @precondition 调用方法的前提条件写在这，分行写。
     * @param xmlstr
     * @return
     * @see xxxClass#xxxMethod
     * @since 1.0
     * @todo 未完成的事项
     */
    private List<CourseInfo> parse(String xmlstr) {
	List<CourseInfo> ret = new ArrayList<CourseInfo>();
	SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
	try {
	    XMLReader xmlReader = saxParserFactory.newSAXParser()
		    .getXMLReader();
	    CourceListContentHandle contentHandle = new CourceListContentHandle(
		    ret);
	    xmlReader.setContentHandler(contentHandle);
	    xmlReader.parse(new InputSource(new StringReader(xmlstr)));
	    return ret;
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return ret;
    }

    /**
     * 将课程xml转化为UnitInfo集合
     * 
     * @precondition 调用方法的前提条件写在这，分行写。
     * @param xmlstr
     * @return
     * @see xxxClass#xxxMethod
     * @since 1.0
     * @todo 未完成的事项
     */
    private List<UnitInfo> parse2Unit(String xmlstr) {
	List<UnitInfo> ret = new ArrayList<UnitInfo>();
	SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
	try {
	    XMLReader xmlReader = saxParserFactory.newSAXParser()
		    .getXMLReader();
	    UnitListContentHandle contentHandle = new UnitListContentHandle(ret);
	    xmlReader.setContentHandler(contentHandle);
	    xmlReader.parse(new InputSource(new StringReader(xmlstr)));
	    return ret;
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return ret;
    }

    /**
     * 通过课程信息的集合构建一个SimpleAdapter
     * 
     * @precondition 调用方法的前提条件写在这，分行写。
     * @param courseInfos
     *            课程信息的集合
     * @return 返回一个SimpleAdapter对象
     * @see xxxClass#xxxMethod
     * @since 1.0
     * @todo 未完成的事项
     */
    @SuppressWarnings("unchecked")
    private SimpleAdapter buildsimpleadaAdapter(List<CourseInfo> courseInfos) {
	SimpleAdapter retAdapter = null;
	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	for (Iterator iterator = courseInfos.iterator(); iterator.hasNext();) {
	    CourseInfo courseInfo = (CourseInfo) iterator.next();
	    Map<String, Object> map = new HashMap<String, Object>();
	    // map.put("ivLogo", R.drawable.icon);
	    map.put("courseName", courseInfo.getMp3Name());
	    map.put("chbCourseName", R.id.chb_course_name);
	    list.add(map);
	    retAdapter = new SimpleAdapter(this, list, R.layout.course_item,
		    new String[] { "courseName", "chbCourseName" }, new int[] {
			    R.id.tv_course_name, R.id.chb_course_name });
	}

	return retAdapter;

    }

    public boolean onGroupClick(ExpandableListView parent, View v,
	    int groupPosition, long id) {
	// TODO Auto-generated method stub
	return false;
    }

    /**
     *当分组行背点击时，让分组呈现“选中／取消选中”状态。
     */
    public boolean onChildClick(ExpandableListView parent, View v,
	    int groupPosition, int childPosition, long id) {

	CourseInfoAdapter.ExpandableListHolder holder = (CourseInfoAdapter.ExpandableListHolder) v
		.getTag();

	holder.chkChecked.setChecked(!holder.chkChecked.isChecked());

	groups.get(groupPosition).getChildren().get(childPosition)
		.setChecked(

			!groups.get(groupPosition).getChildren().get(
				childPosition).isChecked());

	return false;

    }

}
